package org.summerframework.component.security.spring.filter;

import org.summerframework.component.security.context.RequestContextFactory;
import org.summerframework.component.security.core.service.LoginManage;
import org.summerframework.component.security.enumeration.LoginTypeEnum;
import org.summerframework.component.security.spring.exception.UrlAuthenticationFailureHandler;
import org.summerframework.core.util.ViewUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石超
 * @version v1.0.0
 */
public class LogoutHandler implements LogoutSuccessHandler {

    private final LoginManage loginManage;

    private final UrlAuthenticationFailureHandler urlAuthenticationFailureHandler;

    public LogoutHandler(LoginManage loginManage, UrlAuthenticationFailureHandler urlAuthenticationFailureHandler) {
        this.loginManage = loginManage;
        this.urlAuthenticationFailureHandler = urlAuthenticationFailureHandler;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try {
            ModelAndView modelAndView = loginManage.login(RequestContextFactory.getCurrentContext(), LoginTypeEnum.LOGOUT.getType());

            ViewUtil.render(modelAndView, request, response);
        } catch (Exception e) {
            urlAuthenticationFailureHandler.failure(request, response, e);
        }
    }
}
